﻿using MediatR;
using MES.Process.API.Application.Command.工序分类命令;
using MES.Process.Domain;
using MES.Process.ErrorCode;
using MES.Process.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace MES.Process.API.Application.CommandHandler.工序分类命令处理
{
    /// <summary>
    /// 工序分类查询命令处理
    /// </summary>
    public class ProcessTypeQueryCommandHandler : IRequestHandler<ProcessTypeQueryCommand, APIResult<APIPaging<ProcessType>>>
    {
        private readonly ILogger<ProcessTypeQueryCommandHandler> _logger;
        private readonly IBaseRepository<ProcessType> typeRepository;
        public ProcessTypeQueryCommandHandler(ILogger<ProcessTypeQueryCommandHandler> logger, IBaseRepository<ProcessType> typeRepository = null)
        {
            _logger = logger;
            this.typeRepository = typeRepository;
        }

        public async Task<APIResult<APIPaging<ProcessType>>> Handle(ProcessTypeQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<APIPaging<ProcessType>> result = new APIResult<APIPaging<ProcessType>>();

                IQueryable<ProcessType> query = typeRepository.GetValues();

                if (request.PageSize == 0)
                {
                    var allList = await query
                        .OrderByDescending(x => x.CreateTime)
                        .ToListAsync(cancellationToken);

                    result.Code = APIEnums.Success;
                    result.Message = "工序分类查询成功";
                    result.Data = new APIPaging<ProcessType>
                    {
                        List = allList
                    };
                    return result;
                }

                int skip = (request.PageIndex - 1) * request.PageSize;

                int totalCount = await query.CountAsync(cancellationToken);
                var pageList = await query
                    .OrderByDescending(x => x.CreateTime)
                    .Skip(skip)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                result.Code = APIEnums.Success;
                result.Message = "工序分类查询成功";
                var paging = new APIPaging<ProcessType>
                {
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize,
                    TotalCount = totalCount,
                    List = pageList
                };
                paging.TotalPages = (int)Math.Ceiling((double)paging.TotalCount / request.PageSize);
                result.Data = paging;
                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
